var consts;
function draw() {

    dataSource =  new YAHOO.util.LocalDataSource(data);
    var myAutoComp = new YAHOO.widget.AutoComplete("courseInput","autocomplete",dataSource);
    myAutoComp.queryMatchContains = true;
    myAutoComp.queryDelay = 0.01;
    myAutoComp.forceSelection = true;
    myAutoComp.maxResultsDisplayed = 20;
    myAutoComp.formatResult = function(oResultData, sQuery, sResultMatch) {
	return sResultMatch.split(sQuery.toUpperCase()).join("<b>"+sQuery.toUpperCase()+"</b>");
   
    };

    $('#hide').hide();
    $('#right').hide();
    $('#schedule').hide();
    $('#classContainer').hide('slow');
    $('#controls').hide();
    var canvas = document.getElementById("canvas");  
    if (canvas.getContext) { 
        var ctx = canvas.getContext("2d");  
		
	var my_gradient = ctx.createLinearGradient(canvas.height, canvas.width,0,0 );
	my_gradient.addColorStop(0, "white");
	my_gradient.addColorStop(1, "rgb(200,200,200)");
 
	ctx.fillStyle = my_gradient;
 
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	document.getElementById('courseInput').style.color = "gray"
	    }  
	//make sliders
    var days= new Array("m","t","w","th","f");
    for(var i=0;i<5;i++){	eval('$("#'+days[i]+'slider").slider({range: true,min: 800,max: 2000,step: 50,values: [ 800, 2000 ],slide: function( event, ui ) {$("#'+days[i]+'slider").children()[1].innerText = "start:" + (ui.values[0]%100==0)? (ui.values[0]-100)%1200+100 : (ui.values[0]-20-100)%1200+100;$("#'+days[i]+'slider").children()[2].innerText = (ui.values[1]%100==0)? (ui.values[1]-100)%1200+100 : (ui.values[1]-20-100)%1200+100 ;}});');
	$('#'+days[i]+'slider').children()[1].innerText="800";
	$('#'+days[i]+'slider').children()[2].innerText="800";
}    
}

function addOrdering() {
//make sure you cant add the same ordering config twice
//make sure you dont try to add one ordering, and the inverse

	var X = document.getElementById('x').value;
	var Y = document.getElementById('y').value;
		
	//X = X.toLowerCase().replace(" ","");
	//Y = Y.toLowerCase().replace(" ","");
	//consts+="B" + X + Y+",";
		
	if(X!=Y &&  $('div:contains('+X+' before '+Y+')').length==0 &&  $('div:contains('+Y+' before '+X+')').length==0){
		var tag = document.createElement("Bf");
		tag.innerHTML = '<div id="tag" onclick="$(this).hide(200, function () { $(this).remove();  });"> '+X+' before '+Y+'</div>';
		document.getElementById("selectedC").appendChild(tag);			
	}
}
function addTime(day) {
	var start = $( "#"+day+"slider" ).slider( "option", "values" )[0];
	var finish =$( "#"+day+"slider" ).slider( "option", "values" )[1];
	//consts+="RTD "+day+" "+start+" "+finish+",";	
	if( $('div:contains( no classes on '+day+' from '+start+' to '+ finish+')').length==0){
		var tag = document.createElement("RTD");
		tag.innerHTML =  '<div id="tag" onclick="$(this).hide(200, function () { $(this).remove();  });"> no classes on '+day+' from '+start+' to '+ finish+'</div>';
		document.getElementById("selectedC").appendChild(tag); 
	}
} 
function addclass() {
    var classname = document.getElementById('courseInput').value;
	    if(classname !="" &&classname !=document.getElementById('courseInput').defaultValue && $.inArray(classname, data)!=-1){
		var tag = document.createElement("class");
		tag.innerHTML = '<div id="tag" onclick="$(this).hide(200, function () { $(this).parent().remove(); populateSelects();  });"> '+classname+' </div>';
		document.getElementById('classes').appendChild(tag);
		document.getElementById('courseInput').value = "";
		populateSelects();
	}
 
}
function populateSelects(){
    var classes=document.getElementById('classes');
    var l = classes.childElementCount;
    document.getElementById("x").options.length = l-7;
    document.getElementById("y").options.length = l-7;
    if(l==7){
	document.getElementById("x").options[0]=new Option("no classes selected","");
	document.getElementById("y").options[0]=new Option("no classes selected","");}
    for(var i =7;i<l;i++){
	document.getElementById("x").options[i-7]=new Option(classes.children[i].innerText,classes.children[i].innerText);
	document.getElementById("y").options[i-7]=new Option(classes.children[i].innerText,classes.children[i].innerText);
    }
	
}


function clearText(thefield){
    if (thefield.defaultValue==thefield.value){
	thefield.value = ""
	    thefield.style.color = "black";
    }
}
var numClasses=0;
var validResponse=false;
function submit(){
   
    classList = " ";
    classes = document.getElementById('classes')
		 classList+=classes.children[7].innerText;
	for(var i =8;i<classes.childElementCount;i++)
	    classList+=",,"+classes.children[i].innerText;

    document.getElementById("controls").innerHTML= "<h3>loading</h3>";
    consts=generateConstraints();
    
    //$.get("test.py", {classes:classList, constraints:consts}, function (response){ document.getElementById("controls").innerHTML=(response); var data=response.split(","); drawAllClasses(data);});
    xmlhttpPost("/cgi-bin/NTFTRunner/solve.py");
	

} 
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
   self.xmlHttpReq.setRequestHeader('Content-Type', 'text');
    self.xmlHttpReq.onreadystatechange = function() {
      if (self.xmlHttpReq.readyState == 4) {
		
		response =self.xmlHttpReq.responseText;


		if(response.indexOf("UNSATISFIABLE")==-1){
		numClass=0;
		document.getElementById("classContainer").innerHTML = "";
		document.getElementById("controls").innerHTML = response;
		response=response.substring(response.indexOf("["));
		response=response.split("][");
		for(i in response){
			response[i]=response[i].replace(']','').replace('[','').split(") ,(")
			for(j in response[i]){
				response[i][j]=response[i][j].replace(')','').replace('(','').split(",")
			}
		}
		    $('#submitbutton').hide('slow');
		    $('#classes').hide('slow');
		    $('#left').hide('slow');
		    $('#classContainer').show("slow");
		    $('#right').show('slow');	
		    $('#hide').show('slow');
		    $('#schedule').show('slow');
		    $('#controls').show('slow');	
		     drawSchedule();
		drawAllClasses(numClass);
	}
		else{
	alert("schedule has no valid answer sets given constraints, or we fucked something up. please try again we are really sorry seriously. maybe that one class doesn't even exist and we lied to you.");
		}
      }
    }
    self.xmlHttpReq.send(getquerystring());
	
}

function getquerystring() {
	qstr = "class="+classList+"&consts="+consts
	return qstr
}
function generateConstraints(){
c=Array();
var rtds= $("RTD")
	for(i in rtds){
		var s =rtds[i].innerText;
		if(s!=undefined){
		//....yeaaah we're not even sure what's going on here it's 4:30 am and we've been drinking a bit
		day=s.substring(s.indexOf("on")+3).split(" ")
		if(day[2]!=undefined)
		c.push("RTD " + day[0] +" "+ day[2] +" "+ day[4] )
		}
	}

var bs= $("Bf")
	for(j in bs){
		if(bs[j].innerText!=undefined){
		var b = bs[j].innerText.split("before")
		c.push("B "+ (b[0].split(" ").join('').toLowerCase()) +" "+ (b[1].split(" ").join('').toLowerCase()) )
		}
	}
return c.join(",");
}

function sho(){
    $('#classes').show('slow');
    $('#left').show('slow');
    $('#hide').hide('slow');
    $('#right').hide();
    $('#schedule').hide('slow');
    $('#classContainer').hide('slow');
    $('#controls').hide('slow');
    $('#submitbutton').show('slow');
} 


